<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
        <el-dialog width="500px" title="添加角色" :visible.sync="showDialog" @close="close">
          <el-form ref="form" label-width="120px" :model="form" :rules="rules">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" style="width:300px" size="mini" />
            </el-form-item>
            <el-form-item label="启用" prop="state">
              <el-switch v-model="form.state" size="mini" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="form.description" :rows="3" style="width:300px" size="mini" type="textarea" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="addRole">
                确定
              </el-button>
              <el-button size="mini" @click="close">
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色" prop="name">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用" prop="state">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1?'启用':row.state===0?'禁用': '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirm(row)">确定</el-button>
              <el-button size="mini" type="button" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRole(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination layout="prev, pager, next" :total="pageParams.total" :page-size="pageParams.pagesize" :current-page="pageParams.page" @current-change="changePage" />
      </el-row>

    </div>
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree ref="permTree" node-key="id" :default-checked-keys="permIds" show-checkbox :data="permissionList" :props="defaultProps" />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

        </el-col>

      </el-row>
    </el-dialog>
  </div>

</template>

<script>
import { getPermissionList } from '@/api/permission'
import { addRole, assignPerm, deleteRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      list: [],
      showDialog: false,
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      form: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionList: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 记录选中权限列表
      permIds: [],
      // 记录角色id
      currentRoleId: null
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleList(this.pageParams)
      this.list = res.rows
      this.pageParams.total = res.total
      this.list.forEach(item => {
        // 给每条数据添加isEdit和editRow属性
        this.$set(item, 'isEdit', false)
        // 复制一份原始数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页
    changePage(page) {
      this.pageParams.page = page
      this.getRoleList()
    },
    // 添加角色
    addRole() {
      this.$refs.form.validate(async(valid) => {
        await addRole(this.form)
        this.$message.success('添加角色成功')
        this.getRoleList()
        this.close()
      })
    },
    // 点击编辑
    editRole(row) {
      row.isEdit = true
      // 复制一份原始数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 编辑角色-确定
    async confirm(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ id: row.id, ...row.editRow })
        this.$message.success('修改角色成功')
        Object.assign(row, {
          isEdit: false,
          ...row.editRow
        })
      }
    },
    // 删除角色
    async delRole(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 分配权限
    async btnPermission(id) {
      this.permissionList = transListToTreeData(await getPermissionList(), 0)
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.currentRoleId = id
      this.showPermissionDialog = true
    },
    // 确定分配权限
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    // 关闭弹窗
    close() {
      this.$refs.form.resetFields()
      this.showDialog = false
    }
  }
}
</script>
<style scoped>
  .role-operate {
  padding: 10px;
}
</style>

